import { delNovelUsingPost, listByUserIdUsingGet } from "@/services/novel-web/novelController";
import { MessageError, ToLogin } from "@/utils/commonUtils";
import { BookOutlined, EditOutlined, ExclamationCircleFilled, HeartOutlined, UploadOutlined, UserOutlined } from "@ant-design/icons";
import { history, useLocation, useModel } from "@umijs/max";
import { Avatar, Button, Card, Col, Divider, Input, Layout, List, Menu, message, Modal, Row, Upload } from "antd";
import Meta from "antd/es/card/Meta";
import { Content } from "antd/es/layout/layout";
import Sider from "antd/es/layout/Sider";
import { useEffect, useLayoutEffect, useState } from "react";

import { listCollectByUserIdUsingGet } from "@/services/novel-web/collectController";
import ChapterManage from "./ChapterManage/ChapterManage";
import CreateNovel from "./CreateNovel/CreateNovel";
import styles from './index.less';
import NovelSettings from "./NovelSettings/NovelSettings";
import AvatarWithOverlay from "@/components/AvatarWithOverlay";
import { uploadImgUsingPost } from "@/services/novel-web/fileController";
import { updateUserUsingPost } from "@/services/novel-web/userController";




export enum TabName {
  PROFILE ="profile",
  POSTS = "posts",
  FAVORS = "favorites",
  
  // hide in menu
  CREATE = "create-book", 
  SETTINGS = 'settings',
  MANAGE = "chapter-manage",
  
};

const UserHome: React.FC = () =>{

  // logined
  const {initialState,setInitialState} = useModel('@@initialState')
  useEffect(()=>{
    if(initialState && initialState.currentUser) {
      return;
    }
    ToLogin();
  },[initialState?.currentUser]);

 
  // collects
  const [collects,setCollects] = useState<API.NovelVO[]>([]);
  const loadCollects = async (userId:number) => {
    try {
      const resp = await listCollectByUserIdUsingGet({
        userId: userId,
      });

      setCollects(resp.data ?? []);
    } catch (error) {
      MessageError(error);
    }
  };

  const handleNovelClick = (novelId:number) =>{
    history.push(`/novel/${novelId}`);
  }

  // render tabs menu
  // 当前选中的菜单项
  const [selectedMenu, setSelectedMenu] = useState<string>(TabName.POSTS); 

  // posts
  const [posts,setPosts] = useState<API.NovelVO[]>([]);
  const loadPosts = async (userId:number)=>{
    try {
      const resp = await listByUserIdUsingGet({
        userId: userId,
      });
      setPosts(resp.data ?? []);

    } catch (error) { 
      MessageError(error);
    }
  };

  const handlePostClick = (novelId:number) =>{
    history.push(`/novel/${novelId}`);
  }
  const [clickedNovelId,setClickedNovelId]= useState<number>(-1);
  

  // lazy load datas
  useEffect(()=>{
    switch (selectedMenu) {
      case TabName.POSTS:
        loadPosts(initialState?.currentUser?.id ?? -1);
        break;
      case TabName.FAVORS:
        loadCollects(initialState?.currentUser?.id ?? -1);
        break;
      default:
        break;
    }
  },[selectedMenu]);

  //del-btn
  const handleNovelDel = (item:API.NovelVO)=>{
    Modal.confirm({
      title: '确定删除该章节内容？',
      icon: <ExclamationCircleFilled />,
      content: '删除该章节内容后无法撤回',
      onCancel() {},
      onOk() {
        toDelNovel(item);
      },
      
    });
  };
  const toDelNovel = async (item:API.NovelVO)=>{
    try {
      const resp = await delNovelUsingPost({
        id: item.id ?? -1,
      });
      if(resp) {
        setPosts(posts.filter(post => post.id != item.id));
        message.success("删除成功");
      }
    } catch (error) {
      MessageError(error);
    }
  };

  // profile
  // uploadAvatar
  const handleUpload = async (file)=>{
    try {
      const resp = await uploadImgUsingPost({
        file: file,
      })
      if(resp.data) {
        const resp1 = await updateUserUsingPost({
          avatar: resp.data,
        })

        if(resp1.data) {
          setInitialState({
            ...initialState,
            currentUser: {
              ...initialState?.currentUser,
              avatar: resp.data,
            }
          });
          message.success('上传成功');
        }
        
      }
      
    } catch (error) {
      MessageError(error);
    }
    
  }
  // update nickname
  const [visible,setVisible] = useState(false);
  const [modalLoading,setModalLoading] = useState(false);
  const [alterNickname,setAlterNickname] = useState<string>('');
  const handleNickNameAlter = async ()=>{
    const str = alterNickname.trim();
    if(str.length <=2 || str.length >30) {
      message.error("字数不符合格式: 2<len<30");
      return;
    }
    setModalLoading(true);
    try {
      const resp = await updateUserUsingPost({
        nickname: str,
      })
      if(resp.data) {
        setInitialState({
          ...initialState,
          currentUser: {
            ...initialState?.currentUser,
            nickname: str,
          }
        });
        message.success('修改成功');
      }
    } catch (error) {
      MessageError(error);
    } finally{
      setModalLoading(false);
      setVisible(false);
      
    }
  }

  const menuItems = [
    {
      key: TabName.POSTS,
      icon: <BookOutlined />,
      label: '作品管理',
    },
    {
      key: TabName.FAVORS,
      icon: <HeartOutlined />,
      label: '我的收藏',
    },
    {
      key: TabName.PROFILE,
      icon: <UserOutlined />,
      label: '个人资料',
    },
  ];
  

  // initial tab
  const location = useLocation();
  useLayoutEffect(()=>{
    const {initTab, novelId} = location.state as {initTab: string,novelId:string} || {};
    if(initTab) {
      setSelectedMenu(initTab);
    }
    if(novelId) {
      setClickedNovelId(Number(novelId));
    }
    
    return (()=>{
      location.state = null;
    })
  },[])




  // 根据选中的菜单项渲染内容
  const renderContent = () => {
    switch (selectedMenu) {
      case TabName.PROFILE:
        return (
          <Card>
            <Meta
              avatar={
                <AvatarWithOverlay 
                  size={64} src={initialState?.currentUser?.avatar ?? ''} 
                  icon={
                    <Upload
                      customRequest={({file,onSuccess,onError})=>{
                        handleUpload(file).then().catch(onError);
                      }}
                      showUploadList={false}
                    >
                      <UploadOutlined/>
                    </Upload>
                  }
                  tooltip="上传自定义头像"
                />
              }
              title={
                <div>
                  <span>{initialState?.currentUser?.nickname}</span>
                  <EditOutlined
                    style={{marginLeft: '4px'}} 
                    onClick={()=>{
                      setVisible(true);
                      setAlterNickname(initialState?.currentUser?.nickname ?? '');
                    }}
                  />
                </div>
              }
              description={''}
            />
            <div style={{ marginTop: '16px' }}>
              <div></div>
              <br/>
              <div></div>
            </div>
            {/* modal */}
            <Modal
              title="修改昵称"
              open={visible}
              // onOk={handleNickNameAlter}
              confirmLoading={modalLoading}
              footer={[
                <Button key="back" onClick={()=>setVisible(false)}>取消</Button>,
                <Button
                  key="submit"
                  type="primary"
                  onClick={handleNickNameAlter}
                >
                  确定
                </Button>,
              ]}
            >
              <Input
                value={alterNickname}
                onChange={(e) => setAlterNickname(e.target.value)}
              />
            </Modal>
          </Card>
        );
      case TabName.FAVORS:
        return (
          <List
            grid={{column: 7}}
            dataSource={collects}
            renderItem={(item)=>(
              <Col className={styles.item}
                onClick={()=>handleNovelClick(item.id ?? -1)}
              >
                <img src={item.cover} className={styles.cover}/>
                <div className={styles.text}>{item.name}</div>
              </Col>
            )}
          />
        );
      case TabName.POSTS:
        return (<>
          <Row align={"middle"} justify={"space-between"} style={{margin: 8}}>
            <div style={{fontWeight:"bolder", fontSize: 16}}>{"我的作品"}</div>
            <Button
              type="primary"
              onClick={()=>setSelectedMenu(TabName.CREATE)}
            >
              {"新建作品"}
            </Button>
          </Row>
          <Divider/>
          <List
            grid={{column: 1}}
            dataSource={posts}
            renderItem={(item)=>(
              <Row className={styles.item}>
                <Col onClick={()=>handlePostClick(item.id ?? -1)}>
                  <img src={item.cover} className={styles.cover}/>
                </Col>
                <Col className={styles.content}>
                  
                  <div className={styles.text}
                    onClick={()=>handlePostClick(item.id ?? -1)}
                  >
                    {item.name}
                  </div>
                  
                  <Row className={styles.btns}>
                    <Button
                      onClick={()=>{
                        setClickedNovelId(item.id ?? -1);
                        setSelectedMenu(TabName.SETTINGS);
                      }}
                    >
                      {"作品设置"}
                    </Button>

                    <Button
                      style={{marginLeft: '4px'}}
                      onClick={()=>{
                        setClickedNovelId(item.id ?? -1);
                        setSelectedMenu(TabName.MANAGE);
                      }}
                    >
                      {"章节管理"}
                    </Button>

                    <Button
                      style={{marginLeft: '4px'}}
                      onClick={()=>{
                        history.push(`/writer/new-chapter/${item.id}`);
                      }}
                    >
                      {"创建章节"}
                    </Button>

                    <Button
                      style={{marginLeft: '4px'}}
                      onClick={()=>{
                        handleNovelDel(item);
                      }}
                    >
                      {"删除作品"}
                    </Button>
                  </Row>
                </Col>
              </Row>
            )}
          />
        </>);
      case TabName.CREATE:
        return (
          <CreateNovel />
        );
      case TabName.SETTINGS:
        return (
          <NovelSettings novelId={clickedNovelId}/>
        );
      case TabName.MANAGE:
        return (
          <ChapterManage novelId={clickedNovelId}/>
        );
      default:
        return null;
    }
  };

  return (
  <Layout style={{ minHeight: '100vh' }}>
  
    <Layout>
      {/* 侧边栏导航菜单 */}
      <Sider width={200} style={{ background: '#fff' }}>
        <Menu
          mode="inline"
          selectedKeys={[selectedMenu]}
          onClick={({ key }) => setSelectedMenu(key)}
          items={menuItems}
        />
      </Sider>

      {/* 内容区域 */}
      <Content style={{ padding: '12px', background: '#f0f2f5' }}>
        <div style={{ background: '#fff', padding: '24px', minHeight: '280px' }}>
          {renderContent()}
        </div>
      </Content>
    </Layout>
  </Layout>
  );
};

export default UserHome;